package com.yuanfeng.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.constant.RedisConstants;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.excel.Constants;
import com.yuanfeng.commoms.util.querypage.PageHelper;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.base.BaseSysConfigsVO;
import com.yuanfeng.commoms.vo.base.PlatformoperationVO;
import com.yuanfeng.commoms.vo.goods.PlatFormGoodsCatsVO;
import com.yuanfeng.commoms.vo.goodscat.GoodsCatSearchChildVO;
import com.yuanfeng.commoms.vo.goodscat.WebCatMenuVO;
import com.yuanfeng.commoms.vo.shop.ApplyCatVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.goods.dto.ManageItemCatQueryDTO;
import com.yuanfeng.goods.dto.PlatFormGoodsCatsDTO;
import com.yuanfeng.goods.dto.ShopClassBindQueryDTO;
import com.yuanfeng.goods.entity.*;
import com.yuanfeng.goods.feign.BusinessServiceClient;
import com.yuanfeng.goods.mapper.*;
import com.yuanfeng.goods.service.GoodsCatService;
import com.yuanfeng.goods.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName GoodsCatServiceImpl
 * @Description 店铺商品分类
 * @Author cf
 * @Date 2023/6/6 15:40
 * @Version 1.0
 */
@Service
public class GoodsCatServiceImpl extends ServiceImpl<GoodsCatMapper, GoodsCatEntity>
        implements GoodsCatService {

    @Autowired
    private GoodsCatMapper goodsCatMapper;

    @Autowired
    private GoodsBaseMapper goodBaseMapper;

    @Autowired
    private GoodsAttributeMapper goodsAttributeMapper;

    @Autowired
    private GoodsAttributeContentMapper goodsAttributeContentMapper;

    @Autowired
    private GoodsBrandMapper goodsBrandMapper;

    @Autowired
    private GoodsBrandCatMapper goodsBrandCatMapper;

    @Autowired
    private BusinessServiceClient businessServiceClient;

    @Override
    public Integer queryParentCatId(ShopClassBindQueryDTO param) {
        return goodsCatMapper.queryParentCatId(param);
    }

    @Override
    public Integer queryChildCount(Integer param) {
        return goodsCatMapper.queryChildCount(param);
    }

    @Override
    public ResponseResult queryAllCat(Integer shopId) {
        List<ManageShopCatMenuVO> menuLists = new ArrayList<ManageShopCatMenuVO>();
        // 从缓存中查找
        String str = RedisUtil.get(Constants.CACHE_GOODS_CAT_MANAGE_ALL);

        if (null != str && !str.equals("")) {
            List<ManageShopCatMenuVO> redisResult = JsonUtils.string2Obj(str, List.class, ManageShopCatMenuVO.class);
            return ResponseResult.success(redisResult);
        }
        // 查询店铺的所有分类
        List<ManageShopCatMenuVO> rootMenus = goodsCatMapper.selectAllCat2();
        menuLists = getMenuList3(rootMenus);
        // 存入缓存
        RedisUtil.set(Constants.CACHE_GOODS_CAT_MANAGE_ALL, JsonUtils.toString(menuLists), RedisUtil.EXRP_MONTH);
        return ResponseResult.success(menuLists);
    }

    /**
     * 找出一级菜单和二级菜单
     *
     * @param rootMenus
     * @return
     */
    public List<ManageShopCatMenuVO> getMenuList3(List<ManageShopCatMenuVO> rootMenus) {
        List<ManageShopCatMenuVO> list = new ArrayList<ManageShopCatMenuVO>();
        // 先找到所有的一级菜单
        for (int i = 0; i < rootMenus.size(); i++) {
            ManageShopCatMenuVO menu = rootMenus.get(i);
            // 一级菜单 没有父节点
            if (menu.getCatParentId() == 0) {
                list.add(menu);
            }
        }

        // 查找二级菜单
        /**
         * 利用递归找出所有子菜单
         */
        for (ManageShopCatMenuVO menu : list) {
            menu.setChildMenu(getChild3(menu.getCatId(), rootMenus));
        }
        return list;
    }

    /**
     * 找出子菜单
     *
     * @param
     * @param rootMenu
     * @return
     */
    private List<ManageShopCatMenuVO> getChild3(Integer parentId, List<ManageShopCatMenuVO> rootMenu,BigDecimal refundRatio) {
        // 子菜单
        List<ManageShopCatMenuVO> childList = new ArrayList<ManageShopCatMenuVO>();

        for (ManageShopCatMenuVO menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (!StringUtils.isEmpty(menu.getCatParentId())) {
                if (menu.getCatParentId().equals(parentId)) {
                    if (menu.getRefundRatio() == null){
                        menu.setRefundRatio(refundRatio);
                    }
                    childList.add(menu);
                }
            }
        }

        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }

        // 把子菜单的子菜单再循环一遍
        for (ManageShopCatMenuVO menu : childList) {
            // 递归
            menu.setChildGoodsCatList(getChild3(menu.getCatId(), rootMenu,menu.getRefundRatio()));
        }

        return childList;
    }

    /**
     * 找出子菜单
     *
     * @param parentId
     * @param rootMenu
     * @return
     */
    private List<ManageShopCatMenuVO> getChild3(Integer parentId, List<ManageShopCatMenuVO> rootMenu) {
        // 子菜单
        List<ManageShopCatMenuVO> childList = new ArrayList<ManageShopCatMenuVO>();

        for (ManageShopCatMenuVO menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (!StringUtils.isEmpty(menu.getCatParentId())) {
                if (menu.getCatParentId().equals(parentId)) {
                    childList.add(menu);
                }
            }
        }

        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }

        // 把子菜单的子菜单再循环一遍
        for (ManageShopCatMenuVO menu : childList) {
            // 递归
            menu.setChildMenu(getChild3(menu.getCatId(), rootMenu));
        }

        return childList;
    }

    @Override
    public ResponseResult queryItemCat(ManageItemCatQueryDTO param) {
        List<ManageCatVO> goodsCats = new ArrayList<ManageCatVO>();

        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        // if (userPermissionsResult.getFlag()) {
        Integer catParentId = param.getCatParentId();
        goodsCats = goodsCatMapper.selectByCatParentId(catParentId, userInfo.getShopType());

        return ResponseResult.success(goodsCats);
    }


    @Override
    public ResponseResult queryByRuzhu(ManageItemCatQueryDTO param){

        String userInfoStr = RedisUtil.get(RedisConstants.FKGOU_USER_TOKEN_USER + param.getToken());
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if (null == userInfoStr || userInfoStr.equals("")) {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        if(null != userInfo){

            Integer catLevel = param.getCatLevel();
            Integer shopId = Integer.valueOf(userInfo.getShopId());
            //查询一级分类
            if(1 == catLevel){
                //查询商家入职的分类
                List<Integer> ruZhuCatids = goodsCatMapper.queryRuZhuCat(shopId);
                Set<Integer> catResults = new HashSet<>();
                if(null != ruZhuCatids && ruZhuCatids.size()> 0){
                    for (Integer catid : ruZhuCatids) {
                        this.queryParentCat(catid,catResults);
                    }
                }
                if(null == catResults || ruZhuCatids.size() ==  0){
                    return ResponseResult.success();
                }else{
                    List<ManageCatVO> manageCatParent = goodsCatMapper.queryByCatIds2(catResults);
                    return ResponseResult.success(manageCatParent);
                }
                //查询二级分类
            }else if(2 == catLevel){
                //查询商家入职的分类
                List<Integer> ruZhuCatids = goodsCatMapper.queryRuZhuCat(shopId);
                //根据一级分类id 查询所有二级分类
                List<Integer> catids = goodsCatMapper.queryByPranent(param.getCatParentId());
                if(null != ruZhuCatids && ruZhuCatids.size() > 0 && null != catids && catids .size() > 0 ){
                    //根据入职的分类id查询入职分类的上级id
                    List<Integer> ruZhuCatidPranent = goodsCatMapper.queryRuZhuPranentCat(ruZhuCatids);
                    // 两个分类取交集
                    List<Integer>  jiaoList = new ArrayList<>(ruZhuCatidPranent);
                    jiaoList.retainAll(catids);
                    if(null != jiaoList && jiaoList.size() > 0 ){
                        List<ManageCatVO> manageCatParent = goodsCatMapper.queryByCatIds(jiaoList);
                        return ResponseResult.success(manageCatParent);
                    }else{
                        return ResponseResult.success();
                    }
                }
                //查询三级分类
            }else if(3 == catLevel){
                //查询商家入职的分类
                List<Integer> ruZhuCatids = goodsCatMapper.queryRuZhuCat(shopId);
                //根据前端传入的二级类目查询三级
                List<Integer> catids = goodsCatMapper.queryByPranent(param.getCatParentId());
                catids.add(param.getCatParentId());
                if(null != ruZhuCatids && ruZhuCatids.size() > 0 && null != catids && catids .size() > 0 ){
                    // 两个分类取交集
                    List<Integer>  jiaoList = new ArrayList<>(ruZhuCatids);
                    jiaoList.retainAll(catids);
                    if(null != jiaoList && jiaoList.size() > 0 ){
                        List<ManageCatVO> manageCatParent = goodsCatMapper.queryByCatIds(jiaoList);
                        return ResponseResult.success(manageCatParent);
                    }else{
                        return ResponseResult.success();
                    }
                }
            }

        }else{
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.TOKEN_IS_NULL.getMsg());
        }

        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryGoodsCats(PlatFormGoodsCatsDTO dto) {
        List<ManageShopCatMenuVO> results = null;

        List<ManageShopCatMenuVO> rootMenus = null;
        Map<String, Object> param=new HashMap<>();
        param.put("catShowStatus",dto.getCatShowStatus());
        param.put("catParentId",dto.getCatParentId());
        rootMenus = goodsCatMapper.selectPlatFormCats(param);
        Integer totalCount = goodsCatMapper.selectPlatFormCatsCount(param);
        results = getMenuList3(rootMenus,dto.getCatId());
        if(null != dto.getLimit() && null != dto.getPage()){
            if(null != results){
                int toIndex;
                if (dto.getLimit() * dto.getPage() < results.size()) {
                    toIndex = dto.getLimit() * dto.getPage();
                } else {
                    toIndex = results.size();
                }
                results = results.subList((dto.getLimit() - 1) * dto.getPage(), toIndex);
            }

            // 设置缓存
            // RedisUtil.set(Constants.CACHE_PLATFORM_GOODS_ALL_CARS_QUERY,
            // JsonUtils.toString(results));
            HashMap<String,Object> map = new HashMap<>();
            map.put("data",results);
            map.put("totalCount",totalCount);
            return ResponseResult.success(map);
        }

        return ResponseResult.success(results);
    }



    @Override
    public ResponseResult goodscat(Map<String,Object> map) {
        IPage<GoodsCatEntity> page=this.baseMapper.getGoodscatByPage(new Query<GoodsCatEntity>().getPage(map),
                map);

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryNotIntegral(Map<String, Object> map) {
        List<PlatFormGoodsCatsVO> results = null;

        List<PlatFormGoodsCatsVO> rootMenus = null;
        List<Integer> catList = this.baseMapper.getShopCats(map);
        map.put("catShowStatus",1);
        rootMenus = goodsCatMapper.selectPlatFormCatsNotIntegral(Integer.valueOf(map.get("catShowStatus").toString()));
        Integer totalCount = goodsCatMapper.selectPlatFormCatsCountNotIntegral(Integer.valueOf(map.get("catShowStatus").toString()));

        results =getMenuList5(rootMenus,catList);
        //三级分类为空时删除二级分类，二级分类为空时删除一级分类
        results = removeCat(results);

        if(map.get("limit") != null && map.get("page") != null &&Integer.valueOf(map.get("limit").toString()) <= totalCount){
            int limt=Integer.valueOf(map.get("limit").toString());
            int page= Integer.valueOf(map.get("page").toString());
            map.put("limit",(limt - 1) * page);
            if(totalCount < limt+page) {
                map.put("page",page-((limt+page)-totalCount));
            }else if(totalCount == limt+page){
                map.put("page",page-1);
            }else{
                map.put("page",page);
            }
            results = results.subList(limt,limt+page);
            HashMap<String,Object> result = new HashMap<>();
            result.put("data",results);
            result.put("totalCount",totalCount);
            return ResponseResult.success(result);
        }
        // 设置缓存
        // RedisUtil.set(Constants.CACHE_PLATFORM_GOODS_ALL_CARS_QUERY,
        // JsonUtils.toString(results));
        return ResponseResult.success(results);
    }

    @Override
    public ResponseResult queryByGoodsCatId(Integer catId, Integer goodsType, String token) {
        // 获取分类id
        GoodsCatSearchChildVO goodsCatSearchChild = null;
        List<WebCatMenuVO> allMenu = null;
        List<Integer> catIds = null;
        if (null != catId) {

            // 从缓存中获取
            String cacheCatIds = RedisUtil.get(Constant.CACHE_GOODS_WEB_GOODS_LIST_HEADER_PREFIX + "_" + catId);
            // 查询所有下级分类
            allMenu = this.baseMapper.selectAllCat();
            if (null != cacheCatIds && !cacheCatIds.equals("")) {
                goodsCatSearchChild = JsonUtils.string2Obj(cacheCatIds, GoodsCatSearchChildVO.class);
                catIds = goodsCatSearchChild.getCatIds();
            } else {
                allMenu = this.baseMapper.selectAllCat();
                catIds = getMenuList(allMenu, catId);
                goodsCatSearchChild = new GoodsCatSearchChildVO();
                goodsCatSearchChild.setAllMenu(allMenu);
                goodsCatSearchChild.setCatIds(catIds);
                RedisUtil.set(Constant.CACHE_GOODS_WEB_GOODS_LIST_HEADER_PREFIX + "_" + catId,
                        JsonUtils.toString(goodsCatSearchChild), RedisUtil.EXRP_MONTH);
            }
            catIds.add(catId);
        }

        List<GoodsIdsQueryVO> results = goodBaseMapper.selectByCatIds(catIds,goodsType);
        UserInfoVO userInfo = null;
        if(!StringUtils.isEmpty(token)) {
            userInfo=ParseTokenUtils.getUserInfoByToken(token);
        }
        if(null != userInfo && null != goodsType && 2 == goodsType){
            // 获取所有商品店铺信息
            List<Integer> goodsShopIdList = results.stream().map(GoodsIdsQueryVO::getShopId).distinct().collect(Collectors.toList());
            // 查询登录用户已申请经销商成功的店铺id
            List<BaseDealerApplyInfoVO> dealerApplyInfoList =  this.goodsCatMapper.queryDealerApplyListByShop(userInfo.getShopId(),goodsShopIdList);
            if(!CollectionUtils.isEmpty(dealerApplyInfoList)) {
                goodsShopIdList = dealerApplyInfoList.stream().map(BaseDealerApplyInfoVO::getSupplierShopId).distinct().collect(Collectors.toList());
                for (GoodsIdsQueryVO goods : results) {
                    // 商品无需申请经销商
                    if (null != goods.getSellCheck() && goods.getSellCheck().intValue() == 2) {
                        goods.setOperateType(goods.getSellDeliver());
                    } else {
                        if (!goodsShopIdList.contains(goods.getShopId())) {
                            goods.setOperateType(CommonType.goodsOperateType.APPLY.getCode());
                        } else {
                            goods.setOperateType(goods.getSellDeliver());
                        }
                    }
                }
            }else{
                for (GoodsIdsQueryVO goods : results) {
                    if(null != goods.getSellCheck()) {
                        if (goods.getSellCheck().intValue() == 1) {
                            goods.setOperateType (CommonType.goodsOperateType.APPLY.getCode());
                        } else {
                            goods.setOperateType (goods.getSellDeliver());
                        }
                    }
                }
            }
        }
        return ResponseResult.success(results);



    }

    @Override
    public ResponseResult queryCatByCatId(Integer catId) {
        GoodsCatEntity currentCat = this.baseMapper.selectOne(new LambdaQueryWrapper<GoodsCatEntity>()
                .eq(GoodsCatEntity::getCatId, catId)
                .eq(GoodsCatEntity::getCatShowStatus, CommonType.commonStatus.YES.getCode()));
        return ResponseResult.success(currentCat);
    }

    @Override
    public ResponseResult queryCatList(Map<String, Object> map) {
        LambdaQueryWrapper<GoodsCatEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (map.get("showStatus") != null && !"null".equals(map.get("showStatus"))) {
            queryWrapper.eq(GoodsCatEntity::getCatShowStatus, map.get("showStatus"));
        }
        if (map.get("catParentId") != null && !"null".equals(map.get("catParentId"))) {
            queryWrapper.eq(GoodsCatEntity::getCatParentId, map.get("catParentId"));
        }
        List<GoodsCatEntity> list = this.baseMapper.selectList(queryWrapper);
        return ResponseResult.success(list);
    }

    @Override
    public List<String> querySonCatByParentId(Integer productClassId) {
        List<String> result = this.baseMapper.querySonCatByParentId(productClassId);
        return result;
    }

    @Override
    public ResponseResult queryIntegralItemCat(Map<String, Object> map) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(map.get("token").toString());
        if (null != userInfo) {
            Integer catParentId = Integer.valueOf(map.get("catParentId").toString());
            // 从数据库查询分类
            List<GoodsCatEntity> goodsCats = this.baseMapper.queryIntegralItemCat(catParentId);

            return ResponseResult.success(goodsCats);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }


    /**
     * 获取商品分类所有的子分类
     *
     * @param allMenu
     * @param catId
     * @return
     */
    public List<Integer> getMenuList(List<WebCatMenuVO> allMenu, Integer catId) {
        List<Integer> allChildCatIds = Lists.newArrayList();

        if (!CollectionUtils.isEmpty(allMenu)) {
            for (WebCatMenuVO catMenu : allMenu) {
                if (catMenu.getCatId().equals(catId)) {
                    allChildCatIds.add(catId);
                    getChild(allMenu, catMenu.getCatId(), allChildCatIds);
                }

            }
        }
        return allChildCatIds;

    }

    /**
     * 根据父级分类id查询所有子级分类
     *
     * @param rootMenus
     * @return
     */
    public List<ManageShopCatMenuVO> getMenuList(List<ManageShopCatMenuVO> rootMenus) {
        // 先找到所有的一级菜单
        List<ManageShopCatMenuVO> childMenu = Lists.newArrayList();
        for (ManageShopCatMenuVO menu : rootMenus) {

            if (menu.getCatParentId().equals(0)) {
                childMenu.add(menu);
            }
        }
        rootMenus.removeAll(childMenu);

        for (ManageShopCatMenuVO goodsCatsMenuList : childMenu) {
            List<ManageShopCatMenuVO> child1 = getChild(goodsCatsMenuList.getCatId(), rootMenus);
            goodsCatsMenuList.setChildGoodsCatList(child1);
        }
        return childMenu;

    }

    /**
     * 找出子菜单
     */
    private List<ManageShopCatMenuVO> getChild(Integer parentId, List<ManageShopCatMenuVO> rootMenu) {
        // 子菜单
        List<ManageShopCatMenuVO> childList = new ArrayList<ManageShopCatMenuVO>();

        for (ManageShopCatMenuVO menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (!StringUtils.isEmpty(menu.getCatParentId().toString())) {
                if (menu.getCatParentId().equals(parentId)) {
//                    PlatFormGoodsCatsVO platFormGoodsCatsVO=new PlatFormGoodsCatsVO();
//                    BeanUtils.copyProperties(platFormGoodsCatsVO, menu);
                    childList.add(menu);
                }
            }
        }
        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        // 把子菜单的子菜单再循环一遍
        for (ManageShopCatMenuVO menu : childList) {
            // 递归
            menu.setChildGoodsCatList(getChild(menu.getCatId(), rootMenu));
        }
        return childList;
    }



    /**
     * 找出子菜单
     *
     * @param parentId
     * @param allMenu
     * @return
     */
    private List<Integer> getChild(List<WebCatMenuVO> allMenu, Integer parentId, List<Integer> allChildCatIds) {

        List<Integer> childList = Lists.newArrayList();
        for (WebCatMenuVO catMenu : allMenu) {
            if (catMenu.getCatParentId().equals(parentId)) {
                allChildCatIds.add(catMenu.getCatId());
                childList.add(catMenu.getCatId());
                getChild(allMenu, catMenu.getCatId(), allChildCatIds);
            }
        }

        if (CollectionUtils.isEmpty(childList)) {
            return null;
        }

        return allChildCatIds;
    }

    //单三级分类为空时删除二级分类，二级分类为空时删除一级分类
    private List<PlatFormGoodsCatsVO> removeCat(List<PlatFormGoodsCatsVO> data){
        if (data != null && data.size()>0){
            Iterator<PlatFormGoodsCatsVO> iterator = data.iterator();
            while(iterator.hasNext()){
                PlatFormGoodsCatsVO platFormGoodsCatsResult = iterator.next();
                List<PlatFormGoodsCatsVO> catList = platFormGoodsCatsResult.getChildGoodsCatList();
                if (catList != null && catList.size()>0) {
                    Iterator<PlatFormGoodsCatsVO> iterator1 = catList.iterator();
                    while(iterator1.hasNext()){
                        PlatFormGoodsCatsVO next = iterator1.next();
                        List<PlatFormGoodsCatsVO> childGoodsCatList = next.getChildGoodsCatList();
                        if (childGoodsCatList == null || !(childGoodsCatList.size()>0)){
                            iterator1.remove();
                        }
                    }
                }  if (catList == null || !(catList.size()>0)){
                    iterator.remove();
                }
            }
        }


        return data;
    }

    public List<PlatFormGoodsCatsVO> getMenuList5(List<PlatFormGoodsCatsVO> rootMenus, List<Integer> catList) {
        List<PlatFormGoodsCatsVO> childMenu = Lists.newArrayList();
        for (PlatFormGoodsCatsVO menu : rootMenus) {

            if (menu.getCatParentId().equals(0)) {
                childMenu.add(menu);
            }
        }
        rootMenus.removeAll(childMenu);

        for (PlatFormGoodsCatsVO goodsCatsMenuList : childMenu) {
            List<PlatFormGoodsCatsVO> child1 = getChild5(goodsCatsMenuList.getCatId(),rootMenus,catList);
            goodsCatsMenuList.setChildGoodsCatList(child1);
        }

        return childMenu;
    }


    private List<PlatFormGoodsCatsVO> getChild5(Integer parentId, List<PlatFormGoodsCatsVO> rootMenu, List<Integer> catList) {
        List<PlatFormGoodsCatsVO> childList = new ArrayList<PlatFormGoodsCatsVO>();

        for (PlatFormGoodsCatsVO menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (!StringUtils.isEmpty(menu.getCatParentId())) {
                if (menu.getCatParentId().equals(parentId)) {
                    if(!catList.contains(menu.getCatId())) {
                        childList.add(menu);
                    }
                }
            }
        }

        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }

        // 把子菜单的子菜单再循环一遍
        for (PlatFormGoodsCatsVO menu : childList) {
            // 递归
            menu.setChildGoodsCatList(getChild5(menu.getCatId(), rootMenu,catList));
        }

        return childList;
    }

    public Set<Integer> queryParentCat(Integer catid, Set<Integer> catResults) {
        //查询当前分类的信息
        ManageCatVO manageCatResult = goodsCatMapper.queryByCatId2(catid);
        if (null != manageCatResult && 0 == manageCatResult.getCatParentId()) {
            catResults.add(manageCatResult.getCatId());
            return catResults;
        }
        //查询当前分类的上级
        ManageCatVO manageCatParent = goodsCatMapper.queryByCatId2(manageCatResult.getCatParentId());
        if (null != manageCatParent && 0 == manageCatResult.getCatParentId()) {
            catResults.add(manageCatResult.getCatId());
            return catResults;
        } else if (manageCatParent == null){
            return catResults;
        } else {
            return queryParentCat(manageCatParent.getCatId(), catResults);
        }
    }

    @Override
    public ResponseResult queryCatListFilter(Map<String, Object> param) {
        if (param.get("shopId") != null && param.get("shopId") != ""){
            //查看店铺类型
            Integer shopType = goodsCatMapper.selectShopType((Integer) param.get("shopId"));
            if (shopType == 3){
                return ResponseResult.success();
            }
        }
        //catid
        Map<String,Object> map = new HashMap<>();
        // 查询所有下级分类
        Integer catId = Integer.parseInt(param.get("catId")+"");
        List<WebCatMenuVO> nextCatIds  = goodsCatMapper.selectByCatParentId2(catId);
        List<Integer> list = new ArrayList<>();
        if (nextCatIds != null && !nextCatIds.isEmpty()){
            for (WebCatMenuVO nextCatId : nextCatIds) {
                List<WebCatMenuVO> nextChinldCatIds  = goodsCatMapper.selectByCatParentId2(nextCatId.getCatId());
                nextCatId.setAllChildCats(nextChinldCatIds);
                list.add(nextCatId.getCatId());
            }
        }
        List<WebCatMenuVO> webCatMenus = new ArrayList<>();

        if (!list.isEmpty()){
            webCatMenus = goodsCatMapper.selectByCatParentId3(list);
        }
        //商品属性查询
        LinkedHashSet<Map<String, Object>> goodsAttributes = null;
        if (webCatMenus == null || webCatMenus.isEmpty()){
            webCatMenus = new ArrayList<>();
            WebCatMenuVO webCatMenu = new WebCatMenuVO();
            webCatMenu.setCatId(catId);
            webCatMenus.add(webCatMenu);
        }

        goodsAttributes = goodsAttributeMapper.selectAttributes(webCatMenus);
        if(null != goodsAttributes && !goodsAttributes.isEmpty()) {
            //根据商品属性id查询属性内容
            for (Map<String,Object> goodsAttribute : goodsAttributes) {
                LinkedHashSet<Map<String,Object>> goodsAttributeContent =  goodsAttributeContentMapper.selectAttContents((Integer) goodsAttribute.get("id"));
                goodsAttribute.put("goodsAttributeContentResults",goodsAttributeContent);
            }
        }
        //品牌查询
        List<GoodsBrandCatParamVO> goodsBrandCatParam = goodsBrandMapper.selectBrandCats(webCatMenus);

        map.put("goodsBrandCatParam",goodsBrandCatParam);
        map.put("gdbGoodsAttParams",goodsAttributes);
        map.put("nextCatIds",nextCatIds);
        return ResponseResult.success(map);
    }

    @Override
    public ResponseResult queryIntegralItemCat(Integer catParentId) {
        List<GoodCatsResultVO> result = null;

        // 从数据库查询分类
        // 获取分类id
        List<Integer> catIds = null;

        List<GoodsCatResultVO> goodsCats = goodsCatMapper.selectIntegralCatByParentId(catParentId);

        result = Lists.newArrayList();
        // 判断是否是二级分类，是获取三级分类
        if (catParentId != 0) {
            for (GoodsCatResultVO goodsCat : goodsCats) {
                GoodCatsResultVO cats = new GoodCatsResultVO();
                // 获取三级菜单
                List<GoodsCatResultVO> threeGoodsCats = goodsCatMapper.selectIntegralCat(goodsCat.getCatId());
                cats.setSecordCatId(goodsCat.getCatId());
                cats.setGdsCats(threeGoodsCats);
                cats.setSecordCatName(goodsCat.getCatName());
                result.add(cats);

            }
        } else {
            GoodCatsResultVO cats = new GoodCatsResultVO();
            cats.setGdsCats(goodsCats);
            result.add(cats);
        }
        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult checkCatName(Map<String, Object> map) {
        String catName = (String) map.get("catName");
        Integer count = this.baseMapper.selectCount(new LambdaQueryWrapper<GoodsCatEntity>().eq(GoodsCatEntity::getCatName,catName));
        return ResponseResult.success(count);
    }

    @Override
    public ResponseResult queryIntegralGoodsCatsAll(PageHelper param) {
        List<ManageShopCatMenuVO> results = null;
        List<ManageShopCatMenuVO> rootMenus = null;
        rootMenus = this.baseMapper.selectIntegralCats();
        Integer totalCount = this.baseMapper.selectIntegralCatsCount();
        //数据解析封装
        results = getMenuList(rootMenus);
        if (param.getPage() != null && param.getLimit() != null && param.getPage() < totalCount) {
            param.setCurrentPage((param.getPage() - 1) * param.getLimit());
            if (totalCount < param.getPage() + param.getLimit()) {
                param.setPageSize(param.getLimit() - ((param.getPage() + param.getLimit()) - totalCount));
            } else if (totalCount == param.getPage() + param.getLimit()) {
                param.setPageSize(param.getLimit() - 1);
            } else {
                param.setPageSize(param.getLimit());
            }
            results = results.subList(param.getPage(), param.getPage() + param.getLimit());
            HashMap<String, Object> map = new HashMap<>();
            map.put("data", results);
            map.put("totalCount", totalCount);
            return ResponseResult.success(map);
        }
        return ResponseResult.success(results);
    }

    @Override
    public ResponseResult addIntegralCat(PlatFormGoodsCatsDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            if (null != param.getCatId()) {
                //修改积分分类
                this.baseMapper.updateIntegralGoodsCat(param);
            } else {
                if (null == param.getCatLevel()) {
                    param.setCatLevel(CommonType.catStart.GRADE_ONE.getCode());
                }
                List<PlatFormGoodsCatsDTO> goodsCats = Lists.newArrayList();
                String[] catNames = param.getCatName().split(",");
                for (String catName : catNames) {
                    param.setCatName(catName);
                    goodsCats.add(param);
                }
                //判读当前添加的类型是否是顶级类型
                if (null == param.getCatParentId() || CommonType.catStart.GRADE_ZERO.getCode().equals(param.getCatParentId())) {
                    //是顶级类型 直接添加
                    this.baseMapper.addIntegralCatsBatch(goodsCats);
                } else {
                    //根据他的上级id 查询他的上级是否允许添加虚拟商品
                    PlatFormGoodsCatsVO platFormGoodsCatsResult = this.baseMapper.selectParentCat(param.getCatParentId());
                    if (platFormGoodsCatsResult.getCatLevel().equals(CommonType.catStart.GRADE_ZERO.getCode())
                            || platFormGoodsCatsResult.getCatLevel().equals(CommonType.catStart.GRADE_ONE.getCode())) {
                        param.setCatLevel(CommonType.catStart.GRADE_TWO.getCode());
                    } else if (platFormGoodsCatsResult.getCatLevel().equals(CommonType.catStart.GRADE_TWO.getCode())) {
                        param.setCatLevel(CommonType.catStart.GRADE_THREE.getCode());
                    }
                    this.baseMapper.addIntegralCatsBatch(goodsCats);
                }
            }
            // 删除分类的缓存
            RedisUtil.remove("GOODS_INTEGRAL_CAT");
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult deleteIntegralCat(PlatFormGoodsCatsDTO param) {
        ResponseResult rr = deleteGoodsCat(param);
        if (rr.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
            return rr;
        }
        // 删除积分分类的缓存
        RedisUtil.remove("GOODS_INTEGRAL_CAT");
        return ResponseResult.success();
    }

    @Override
    public ResponseResult deleteGoodsCat(PlatFormGoodsCatsDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            List<Integer> levelList = new ArrayList<>();
            //根据catId获取分类信息
            GoodsCatEntity cat = this.baseMapper.selectById(param.getCatId());
            if (!cat.getCatLevel().equals(CommonType.catStart.GRADE_THREE.getCode())) {
                //查询子类catId
                levelList = this.baseMapper.selectCatLevel(param.getCatId());
                //如果是1级分类循环查找3级分类id
                if (cat.getCatLevel().equals(CommonType.catStart.GRADE_ZERO.getCode())
                        || cat.getCatLevel().equals(CommonType.catStart.GRADE_ONE.getCode())) {
                    List<Integer> levelIds = new ArrayList<>(levelList);
                    for (Integer integer : levelIds) {
                        List<Integer> list = this.baseMapper.selectCatLevel(integer);
                        if (list.size() != 0) {
                            levelList.addAll(list);
                        }
                    }
                }
            }
            levelList.add(param.getCatId());
            Integer goodsCount = this.baseMapper.selectGoodsCountByCatIds(levelList);
//            //查询当前分类是否 是商家的经营类目
//            if(null != levelList && levelList.size() > 0){
//                goodsCount = goodsCatMapper.queryShopBindCat(levelList);
//            }
            levelList = levelList.stream().filter(Objects::nonNull).collect(Collectors.toList());
            if (goodsCount == 0) {
                for (Integer catId : levelList) {
                    //删除分类
                    this.baseMapper.deleteById(catId);
                    //删除绑定的入驻分类
                    businessServiceClient.deleteBindGoodsCat(catId);
                    businessServiceClient.deleteClassBindTmp(catId);
                }
                // 删除分类的缓存
                RedisUtil.remove("GOODS_CAT");
                RedisUtil.fuzzyDeletion(RedisPrefixUtils.goodsClassify);
                RedisUtil.remove(Constant.CACHE_GOODS_CAT_MANAGE_ALL);
                return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
            }
            return ResponseResult.fail(BizCodeEnume.ELETE_GOODS_CAT_ERROP);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult addGoodsCat(PlatFormGoodsCatsDTO param) {
        if (null == param.getCatCommission()) {
            param.setCatCommission(new BigDecimal(0));
        }

        if (null == param.getBabyCommission()) {
            param.setBabyCommission(new BigDecimal(0));
        }
        if (param.getCatDisplayorder() >255 || param.getCatDisplayorder() <0){
            return ResponseResult.fail(BizCodeEnume.SORTING_VALUE_YOU_ENTERED_IS_OUT_OF_RANGE);
        }
        if (null != param.getCatId()) {
            //修改商品分类
            goodsCatMapper.updateGoodsCat(param);
            //处理品牌数据
            goodsCatBrand(param);
            //处理分类属性
            goodsCatAttribute(param);
        } else {
            if (null == param.getCatLevel()) {
                param.setCatLevel(0);
            }
            //判断当前分类是否是一级分类
            if(null == param.getCatParentId() || 0 == param.getCatParentId()){
                //是一级分类 直接添加
                goodsCatMapper.addPlatFormCatsBatch2(param);
            }else {
                //添加分了信息
                goodsCatMapper.addPlatFormCatsBatch2(param);
                List<Integer> brandIds = param.getBrandIdList();
                //当品牌id 不为null,查询品牌信息 存入分类品牌关联表
                if (null != brandIds && brandIds.size() > 0) {
                    //查询品牌信息
                    List<GoodsBrandEntity> GoodsBrandList = goodsBrandMapper.selectList(new LambdaQueryWrapper<GoodsBrandEntity>().in(GoodsBrandEntity::getBrandId,brandIds));
                    for (GoodsBrandEntity brands : GoodsBrandList) {
                        brands.setCatId(param.getCatId());
                        //存入分类品牌关联表
                        GoodsBrandCatEntity entity=new GoodsBrandCatEntity();
                        entity.setCatId(param.getCatId());
                        entity.setBrandId(brands.getBrandId());
                        entity.setBrandName(brands.getBrandName());
                        entity.setBrandHf(brands.getBrandHf());
                        entity.setBrandPic(brands.getBrandPic());
                        goodsBrandCatMapper.insert(entity);
                    }
                }
                //当前传入的属性名 和 属性内容不为null 存入数据库
                List<GoodsAttributeEntity> goodsAttributeParamList = param.getGoodsAttriParam();
                if (null != goodsAttributeParamList &&goodsAttributeParamList.size() > 0) {
                    for (GoodsAttributeEntity goodsParam : goodsAttributeParamList) {
                        goodsParam.setCatId(param.getCatId());
                        //存入属性名
                        goodsAttributeMapper.insert(goodsParam);
                        if (goodsParam.getAttributeContent().size() > 0) {
                            List<String> attCons = goodsParam.getAttributeContent();
                            for (String attCon : attCons) {
                                GoodsAttributeContentEntity entity=new GoodsAttributeContentEntity();
                                entity.setAttributeContentId(goodsParam.getId());
                                entity.setAttributeContent(attCon);
                                goodsAttributeContentMapper.insert(entity);
                            }

                        }
                    }
                }
            }
        }
        // 删除分类的缓存
        RedisUtil.remove("JAVA_GOODS_CAT_WAP_GOODS_QUERY");
        RedisUtil.remove("GOODS_CAT");
        RedisUtil.remove(Constant.CACHE_GOODS_CAT_MANAGE_ALL);
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }
    /**
     * 处理品牌
     */
    public void goodsCatBrand(PlatFormGoodsCatsDTO param){
        //查询当前分类已绑定的品牌
        List<Integer> bindBrandIds = goodsBrandMapper.querybindBranIds(param.getCatId());
        // 前端传入的品牌
        List<Integer> brandIds =param.getBrandIdList();
        if(bindBrandIds != null && bindBrandIds.size() > 0 && brandIds != null && brandIds.size() > 0   ){
            //新添加的品牌
            List<Integer> addBrandIds = new ArrayList<>();
            //要删除的品牌
            List<Integer> deleteBrandId = new ArrayList<>();
            //已绑定的品牌id是否在 前端传入的list中  不存在就存入deleteBrandId
            for (Integer bindBrandId : bindBrandIds) {
                if(!brandIds.contains(bindBrandId)){
                    deleteBrandId.add(bindBrandId);
                }
            }
            // 前端传入的品牌id  是否在已绑定的品牌中 不存在就存入 addBrandIds
            for (Integer brandId : brandIds) {
                if(!bindBrandIds.contains(brandId)){
                    addBrandIds.add(brandId);
                }
            }
            //删除分类与品牌绑定信息
            if(deleteBrandId.size() > 0){
                goodsBrandCatMapper.deleteBrandIds(deleteBrandId);
            }
            //添加分类与品牌绑定信息
            if(addBrandIds.size() > 0){
                List<GoodsBrandEntity> GoodsBrandList = goodsBrandMapper.selectList(new LambdaQueryWrapper<GoodsBrandEntity>().in(GoodsBrandEntity::getBrandId,brandIds));
                for (GoodsBrandEntity brands : GoodsBrandList) {
                    brands.setCatId(param.getCatId());
                    goodsBrandCatMapper.insertBrandCat(brands);
                }
            }
        }else if ((bindBrandIds == null || bindBrandIds.size() == 0) && brandIds != null && brandIds.size() != 0 ){
            //查询品牌信息 存入数据库
            List<GoodsBrandEntity> GoodsBrandList = goodsBrandMapper.selectList(new LambdaQueryWrapper<GoodsBrandEntity>().in(GoodsBrandEntity::getBrandId,brandIds));
            for (GoodsBrandEntity brands : GoodsBrandList) {
                brands.setCatId(param.getCatId());
                goodsBrandCatMapper.insertBrandCat(brands);
            }
        }
    }
    /**
     * 处理分类属性名  属性值
     * @param param
     */
    public void goodsCatAttribute(PlatFormGoodsCatsDTO param){
        //前端传入 分类属性
        List<GoodsAttributeEntity> goodsAttributeParamList = param.getGoodsAttriParam();
        //查询当前分类 已经添加的分类属性
        List<GoodsAttributeEntity> existGoodsAttribute =goodsAttributeMapper.selectAttribute(param.getCatId());
        if(null != existGoodsAttribute && existGoodsAttribute.size() > 0 ){
            for(GoodsAttributeEntity goodsAtt:existGoodsAttribute){
                //查询当前分类属性值
                List<String> attributeContent = goodsAttributeContentMapper.queryAttributeContentList(goodsAtt.getId());
                goodsAtt.setAttributeContent(attributeContent);
            }
        }

        if((goodsAttributeParamList != null && goodsAttributeParamList.size() > 0)
                && (existGoodsAttribute != null && existGoodsAttribute.size() > 0 )){
            // 前端传入 和 已经添加的分类属性都不为空
            //需要添加的分类属性名
            List<GoodsAttributeEntity> addGoodsAttribute = new ArrayList<>();
            //需要删除的分类属性名
            List<GoodsAttributeEntity> deleteGoodsAttribute = new ArrayList<>();
            //需要修改属性值 数据
            List<GoodsAttributeEntity> updateGoodsAttribute = new ArrayList<>();

            // 解析处要删除的分类属性名 和 对应的值
            for (GoodsAttributeEntity goodsAttributeParam : existGoodsAttribute) {
                if(!goodsAttributeParamList.stream().anyMatch(m -> m.getCommodityAttribute().equals(goodsAttributeParam.getCommodityAttribute()))){
                    deleteGoodsAttribute.add(goodsAttributeParam);
                }
            }
            //解析出要添加的分类属性 和 对应的值
            for (GoodsAttributeEntity goodsAttributeParam : goodsAttributeParamList) {
                if(!existGoodsAttribute.stream().anyMatch(m -> m.getCommodityAttribute().equals(goodsAttributeParam.getCommodityAttribute()))){
                    addGoodsAttribute.add(goodsAttributeParam);
                }else{
                    updateGoodsAttribute.add(goodsAttributeParam);
                }
            }
            //解析出 分类属性名称不变  属性值需要修改
            if(null != updateGoodsAttribute && updateGoodsAttribute.size() > 0){
                for (GoodsAttributeEntity goodsAttributeParam : updateGoodsAttribute) {
                    for (GoodsAttributeEntity existAttributeParam : existGoodsAttribute) {
                        //属性名相同时 判断属性值 是否需要添加或删除
                        if(goodsAttributeParam.getCommodityAttribute().equals(existAttributeParam.getCommodityAttribute())){
                            //前端传入的属性值
                            List<String> attributeContent = goodsAttributeParam.getAttributeContent();
                            //已经添加属性值
                            List<String>  existAttributeContent = existAttributeParam.getAttributeContent();
                            for (String s : attributeContent) {
                                //当前端传入的不在  已经添加的里面 就是添加
                                if(!existAttributeContent.contains(s)){
                                    GoodsAttributeEntity goodsParam = new GoodsAttributeEntity();
                                    goodsParam.setAttributeContentId(goodsAttributeParam.getId());
                                    goodsParam.setAttriContent(s);
                                    //存入属性内容
                                    goodsAttributeContentMapper.insertContent(goodsParam);
                                }
                            }
                            for (String s : existAttributeContent) {
                                //当已经添加的不在 前端传入的 就是删除
                                if(!attributeContent.contains(s)){
                                    goodsAttributeContentMapper.deleteContent(goodsAttributeParam.getId());
                                }
                            }

                        }
                    }
                }
            }

            //删除对应属性名 属性值
            if(null != deleteGoodsAttribute && deleteGoodsAttribute.size() > 0 ){
                for(GoodsAttributeEntity goodsAtt:deleteGoodsAttribute){
                    goodsAttributeContentMapper.deleteContent(goodsAtt.getId());
                    //删除分类属性名
                    goodsAttributeMapper.deleteAttris(goodsAtt.getId());
                }
            }
            // 添加对应属性名 属性值
            if(null != addGoodsAttribute && addGoodsAttribute.size() > 0 ){
                for (GoodsAttributeEntity goodsParam : addGoodsAttribute) {
                    goodsParam.setCatId(param.getCatId());
                    //存入属性名
                    goodsAttributeMapper.insertAttribute(goodsParam);
                    if (goodsParam.getAttributeContent().size() > 0) {
                        List<String> attCons = goodsParam.getAttributeContent();
                        for (String attCon : attCons) {
                            goodsParam.setAttributeContentId(goodsParam.getId());
                            goodsParam.setAttriContent(attCon);
                            //存入属性内容
                            goodsAttributeContentMapper.insertContent(goodsParam);
                        }
                    }
                }
            }
        }else if((goodsAttributeParamList != null && goodsAttributeParamList.size() > 0)
                && (existGoodsAttribute == null || existGoodsAttribute.size() == 0 )){
            // 前端传入的分类属性都不为空 和 已经添加的分类属性为空 直接添加
            if (null != goodsAttributeParamList &&goodsAttributeParamList.size() > 0) {
                for (GoodsAttributeEntity goodsParam : goodsAttributeParamList) {
                    goodsParam.setCatId(param.getCatId());
                    //存入属性名
                    goodsAttributeMapper.insertAttribute(goodsParam);
                    if (goodsParam.getAttributeContent().size() > 0) {
                        List<String> attCons = goodsParam.getAttributeContent();
                        for (String attCon : attCons) {
                            goodsParam.setAttributeContentId(goodsParam.getId());
                            goodsParam.setAttriContent(attCon);
                            //存入属性内容
                            goodsAttributeContentMapper.insertContent(goodsParam);
                        }
                    }
                }
            }
        }else if((goodsAttributeParamList == null || goodsAttributeParamList.size() == 0)
                && (existGoodsAttribute != null && existGoodsAttribute.size() >0 )){
            // 前端传入的分类属性都为空   即删除当前分类的所有属性 已经添加的分类属性不为空
            for(GoodsAttributeEntity goodsAtt:existGoodsAttribute){
                goodsAttributeContentMapper.deleteAttriContents(goodsAtt.getId());
                //删除分类属性名
                goodsAttributeMapper.deleteAttris(goodsAtt.getId());
            }
        }
    }
    @Override
    public ResponseResult queryGoodsCatsAll(PageHelper pageHelper) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(pageHelper.getToken());
        if (null != userInfo) {
            List<ManageShopCatMenuVO> results = null;
            List<ManageShopCatMenuVO> rootMenus = null;
            Map<String, Object> param=new HashMap<>();
//            param.put("isIntegralGoods",0);
            rootMenus = this.baseMapper.selectPlatFormCats(param);
            Integer totalCount = this.baseMapper.selectPlatFormCatsCount(param);
            //数据解析封装
            results = getMenuList(rootMenus);
            if(null != pageHelper.getPage() && null != pageHelper.getLimit()){
                if(null != results){
                    int toIndex;
                    if (pageHelper.getPage() * pageHelper.getLimit() < results.size()) {
                        toIndex = pageHelper.getPage() * pageHelper.getLimit();
                    } else {
                        toIndex = results.size();
                    }
                    results = results.subList((pageHelper.getPage() - 1) * pageHelper.getLimit(), toIndex);
                }
                HashMap<String, Object> map = new HashMap<>();
                map.put("data", results);
                map.put("totalCount", totalCount);
                return ResponseResult.success(map);
            }
            return ResponseResult.success(results);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult queryVirtual(ManageCatResultVO param) {
        ManageCatResultVO goodsCats = this.baseMapper.queryVirtualByCatId(param.getCatId());
        return ResponseResult.success(goodsCats);
    }

    @Override
    public ResponseResult queryRankCat() {
        List<GoodsCatEntity> entities = this.baseMapper.selectList(new LambdaQueryWrapper<GoodsCatEntity>()
                .eq(GoodsCatEntity::getCatParentId, 0)
                .eq(GoodsCatEntity::getIsIntegralGoods, 0)
                .orderByAsc(GoodsCatEntity::getCatDisplayorder,GoodsCatEntity::getCatId));
        return ResponseResult.success(entities);
    }

    @Override
    public ResponseResult queryNoCat(Map<String, Object> param) {
        if(param.get("token")!=null) {
            String token = String.valueOf(param.get("token"));
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
            if(null == userInfo ){
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
            }
            Integer shopId = Integer.valueOf(userInfo.getShopId());

            List<ManageShopCatMenuVO> menuLists = new ArrayList<ManageShopCatMenuVO>();
            List<ManageShopCatMenuVO> returnmenuLists = new ArrayList<ManageShopCatMenuVO>();

            List<ManageShopCatMenuVO> rootMenus = this.baseMapper.selectAllCat1(shopId, String.valueOf(param.get("catName")));

            menuLists =getMenuList3(rootMenus);

            // 使用Stream过滤删除二级菜单下三级菜单为空的情况
            returnmenuLists = menuLists.stream()
                    .map(menu ->  {
                        if (menu.getChildMenu() != null) {
                            List<ManageShopCatMenuVO> updatedSubMenus = menu.getChildMenu().stream()
                                    .filter(subMenu -> subMenu.getChildMenu() != null && !subMenu.getChildMenu().isEmpty())
                                    .collect(Collectors.toList());
                            menu.setChildMenu(updatedSubMenus);
                        }
                        return menu;
                    })
                    .filter(x -> x.getChildMenu() != null && !x.getChildMenu().isEmpty())
                    .collect(Collectors.toList());

            return ResponseResult.success(returnmenuLists);
        }else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_NULL);
        }
    }
    @Override
    public ResponseResult applyCat(Map<String, Object> param) {
        if(param.get("token")!=null) {
            String token = String.valueOf(param.get("token"));
            String batchId = String.valueOf(param.get("batchId"));
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
            if(null == userInfo ){
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
            }
            Integer shopId = Integer.valueOf(userInfo.getShopId());

            if (StringUtils.isEmpty(batchId)) {
                //生成批次id
                StringBuffer id = new StringBuffer();
                DateFormat dFormat3 = new SimpleDateFormat("yyyyMMdd");

                String format = dFormat3.format(new Date());

                Random random = new Random();
                String verificationCode = String.valueOf(random.nextInt(9) + 1);
                for (int i = 0; i < 5; i++) {
                    verificationCode += random.nextInt(10);
                }
                id.append(format).append(verificationCode);
                param.put("batchId",id.toString());
            }
            Integer integer = 0;

            param.put("shopId",shopId);
            param.put("start",1);
            List<Integer> catId = (List) param.get("catId");
            ArrayList<Object> list = new ArrayList<>();
            for (Integer o : catId) {
                HashMap<Object, Object> hashMap = new HashMap<>();
                List<String> querycatname = this.baseMapper.queryCatName(o);
                String s = JSON.toJSONString(querycatname);

                hashMap.put("catId",o);
                hashMap.put("catName",s);

                list.add(hashMap);
            }
            param.put("catId",list);
            if (StringUtils.isEmpty(batchId)) {
                //新增
                integer = this.baseMapper.insertclassbind(param);
            }else{
                //修改
                this.baseMapper.deleteclassbind(param);

                integer = this.baseMapper.insertclassbind(param);
            }

            if (integer > 0){
                return ResponseResult.success("申请成功");
            }
            return ResponseResult.fail(0, "申请失败");
        }else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_NULL);
        }
    }

    @Override
    public ResponseResult qureyApplyCat(Map<String, Object> param) {
        if(param.get("token")!=null) {
            String token = String.valueOf(param.get("token"));
            String batchId = String.valueOf(param.get("batchId"));
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
            if(null == userInfo ){
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
            }
            Integer pageSize = (Integer)param.get("limit");
            Integer shopId = Integer.valueOf(userInfo.getShopId());

            param.put("shopId",shopId);

            // 查询入驻的分类
            List<ApplyCatVO> list = new ArrayList<>();
            List<ApplyCatVO> queryJoinCat = this.baseMapper.queryJoinCat(param);
            if (!CollectionUtils.isEmpty(queryJoinCat)){
                ApplyCatVO catDTO = new ApplyCatVO();
                catDTO.setBatchId("0");
                catDTO.setStart(2);
                for (ApplyCatVO catEntity : queryJoinCat) {
                    List<String> catNameList = this.baseMapper.querySonCatByParentId(catEntity.getCatId());
                    String catName = JSON.toJSONString(catNameList);
                    catEntity.setCatName(catName);
                    catEntity.setCatNames(catNameList);
                }
                catDTO.setCatEntities(queryJoinCat);
                list.add(catDTO);
            }
            IPage<ApplyCatVO> page=this.baseMapper.qureyApplyCat(new Query<ApplyCatVO>().getPage(param),
                    param);

            if (!CollectionUtils.isEmpty(page.getRecords())){
                for (ApplyCatVO applyCatEntity : page.getRecords()) {
                    param.put("batchId",applyCatEntity.getBatchId());
                    List<ApplyCatVO> querycat = goodsCatMapper.querycat(param);
                    if (!CollectionUtils.isEmpty(querycat)){
                        for (ApplyCatVO catEntity : querycat) {
                            String catName = catEntity.getCatName();
                            List<String> strings = JSON.parseArray(catName, String.class);
                            catEntity.setCatNames(strings);
                        }
                    }

                    applyCatEntity.setCatEntities(querycat);
                }
            } else {
                page.setRecords(new ArrayList<>());
            }
            page.getRecords().addAll(list);
            //设置分页
            PageUtils result = PageUtils.getPage(page);
            result.setTotalCount(page.getRecords().size());
            Integer totalPage = (result.getTotalCount() % pageSize) == 0 ? result.getTotalCount() / pageSize : result.getTotalCount() / pageSize + 1;
            result.setTotalPage(totalPage);
            return ResponseResult.success(result);

        }else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_NULL);
        }

    }

    @Override
    public ResponseResult queryCat(Map<String, Object> param) {
        List<ManageShopCatMenuVO> results = null;

        List<ManageShopCatMenuVO> rootMenus = null;
        rootMenus = this.baseMapper.selectPlatFormCats2(Integer.valueOf(param.get("catShowStatus").toString()));

        Integer totalCount =  this.baseMapper.selectPlatFormCatsCount2(Integer.valueOf(param.get("catShowStatus").toString()));
        results = getMenuList3(rootMenus,Integer.valueOf(param.get("catId").toString()));
        if(null != param.get("limit") && null != param.get("page")){
            Integer limit=Integer.valueOf(param.get("limit").toString());
            Integer page=Integer.valueOf(param.get("page").toString());
            if(null != results){
                int toIndex;
                if (limit * page < results.size()) {
                    toIndex =limit * page;
                } else {
                    toIndex = results.size();
                }
                results = results.subList((limit - 1) * page, toIndex);
            }

            // 设置缓存
//            RedisUtil.set(Constants.CACHE_PLATFORM_GOODS_ALL_CARS_QUERY,
//            JsonUtils.toString(results));
            HashMap<String,Object> map = new HashMap<>();
            map.put("data",results);
            map.put("totalCount",totalCount);
            return ResponseResult.success(map);
        }

        return  ResponseResult.success(results);
    }

    @Override
    public ResponseResult queryGoodsCatByCatId(Map<String, Object> map) {
        List<GoodsCatEntity> catMap = this.baseMapper.selectList(new LambdaQueryWrapper<GoodsCatEntity>()
                                      .eq(GoodsCatEntity::getCatParentId,map.get("catId").toString())
                                      .eq(GoodsCatEntity::getIsIntegralGoods,0));
        return ResponseResult.success(catMap);
    }

    @Override
    public ResponseResult queryFxCatList(Integer catId) {
        List<Integer> catIds;
        List<WebCatMenuVO> allMenu;
        GoodsCatSearchChildVO goodsCatSearchChild;
        // 从缓存中获取
        String cacheCatIds = RedisUtil.get(Constants.CACHE_GOODS_WEB_GOODS_LIST_HEADER_PREFIX + "_" + catId);
        if (null != cacheCatIds && !cacheCatIds.equals("")) {
            goodsCatSearchChild = JsonUtils.string2Obj(cacheCatIds, GoodsCatSearchChildVO.class);
            catIds = goodsCatSearchChild.getCatIds();
        } else {
            allMenu = this.baseMapper.selectAllCat();
            catIds = getMenuList(allMenu, catId);
            goodsCatSearchChild = new GoodsCatSearchChildVO();
            goodsCatSearchChild.setAllMenu(allMenu);
            goodsCatSearchChild.setCatIds(catIds);
            RedisUtil.set(Constants.CACHE_GOODS_WEB_GOODS_LIST_HEADER_PREFIX + "_" + catId, JsonUtils.toString(goodsCatSearchChild), RedisUtil.EXRP_MONTH);
        }
        if (!CollectionUtils.isEmpty(catIds)) {
            catIds.add(catId);
        }
        return ResponseResult.success(JSON.toJSONString(catIds));
    }

    /**
     * 根据父级分类id查询所有子级分类
     *
     * @param rootMenus
     * @return
     */
    public List<ManageShopCatMenuVO> getMenuList3(List<ManageShopCatMenuVO> rootMenus,Integer catId) {
        //PlatFormGoodsCatsResult result = new PlatFormGoodsCatsResult();
        // 先找到所有的一级菜单
        //查询平台默认质保金
        List<BaseSysConfigsVO> pos =
                this.baseMapper.selectByConfigType("retention_money_default_limit");
        String amount = null;
        if (pos != null && pos.size() > 0){
            amount = pos.get(0).getConfigValue();
        }

        List<BaseSysConfigsVO> pos1 =
                this.baseMapper.selectByConfigType("platform_operation_specifications");
        PlatformoperationVO platformoperationEntity = new PlatformoperationVO();
        if (pos != null && pos1.size() > 0){
            String configValue = pos1.get(0).getConfigValue();
            platformoperationEntity = JSONObject.parseObject(configValue, PlatformoperationVO.class);
        }

        List<ManageShopCatMenuVO> childMenu = Lists.newArrayList();
        if (catId != null) {
            for (ManageShopCatMenuVO menu : rootMenus) {

                if (menu.getCatParentId().equals(0) && menu.getCatId().equals(catId)) {
                    childMenu.add(menu);
                }
            }
        }else{
            for (ManageShopCatMenuVO menu : rootMenus) {
                if (menu.getRefundRatio() == null){
                    menu.setRefundRatio(new BigDecimal(amount));
                }
                if (menu.getRefundProportion() == null){
                    menu.setRefundProportion(platformoperationEntity.getUniversalRatio());
                }
                if (menu.getCatParentId().equals(0)) {
                    childMenu.add(menu);
                }
            }
        }
        rootMenus.removeAll(childMenu);

        for (ManageShopCatMenuVO goodsCatsMenuList : childMenu) {
            List<ManageShopCatMenuVO> child1 = getChild3(goodsCatsMenuList.getCatId(),rootMenus,goodsCatsMenuList.getRefundRatio());
            goodsCatsMenuList.setChildGoodsCatList(child1);
        }

        return childMenu;

    }


}
